'''
https://leetcode.cn/problems/diameter-of-binary-tree/description/
'''
from typing import Optional


class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right

class Solution:
    def diameterOfBinaryTree(self, root: Optional[TreeNode]) -> int:
        def f(root):
            if not root:
                # 当前树的高度，当前树最大直径
                return 0, 0
            lheight, p1 = f(root.left)
            rheight, p2 = f(root.right)
            height = max(lheight, rheight) + 1
            p3 = lheight + rheight
            return height, max(p1, p2, p3)
        return f(root)[1]

    def diameterOfBinaryTree2(self, root: Optional[TreeNode]) -> int:
        ans = 0
        def f(root):
            if not root:
                return 0
            l = f(root.left)
            r = f(root.right)
            height = max(l, r) + 1
            nonlocal ans
            ans = max(ans, height - 1)
            return height
        f(root)
        return ans